//
//  JKImageBrowserView.m
//  ZhiHuDaily
//
//  Created by albert on 16/8/20.
//  Copyright © 2016年 albert. All rights reserved.
//

#import "JKImageBrowserView.h"
#import "UIImageView+WebCache.h"
#import "JKProgressHUD.h"
//#import "JKTopWindowViewController.h"

@interface JKImageBrowserView () <UIScrollViewDelegate>{
    BOOL isGonnaDismiss;
}
/** 图片 */
@property (nonatomic, strong) UIImage *image;

/** 图片url */
@property (nonatomic, copy) NSString *imageUrlStr;

/** imageView */
@property (nonatomic, weak) UIImageView *imageView;

/** scrollView */
@property (nonatomic, weak) UIScrollView *scrollView;

/** 保存按钮 */
@property (weak, nonatomic) UIButton *saveButton;

/** 旋转菊花 */
@property (nonatomic, weak) UIActivityIndicatorView *indicatorView;

/** 夜间模式遮盖view */
@property (nonatomic, weak) UIView *maskView;

/** 当前的ZoomScale */
@property (nonatomic, assign) CGFloat currentZoomScale;

/** 是否双击 */
@property (nonatomic, assign) BOOL isDoubleTap;

/** 是否正在缩放 */
@property (nonatomic, assign) BOOL isZooming;
@end

@implementation JKImageBrowserView

static CGFloat const animationDuration = 0.5;
static CGFloat const bgAlpha = 0.7;

#pragma mark - 外部方法
/** 根据image显示图片 */
+ (void)showWithImage:(UIImage *)image{
    JKImageBrowserView *imageBrowserView = [[JKImageBrowserView alloc] init];
    
    imageBrowserView.image = image;
    
    [[UIApplication sharedApplication].keyWindow.rootViewController.view addSubview:imageBrowserView];
}

/** 根据imageUrlStr显示图片 */
+ (void)showWithImageUrlStr:(NSString *)imageUrlStr{
    JKImageBrowserView *imageBrowserView = [[JKImageBrowserView alloc] init];
    
    imageBrowserView.imageUrlStr = imageUrlStr;
    
    [[UIApplication sharedApplication].keyWindow.rootViewController.view addSubview:imageBrowserView];
}

#pragma mark - 懒加载
- (UIView *)maskView{
    if (!_maskView) {
        UIView *maskView = [[UIView alloc] init];
        maskView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:bgAlpha];
        maskView.userInteractionEnabled = NO;
        [self.imageView addSubview:maskView];
        _maskView = maskView;
    }
    return _maskView;
}

//- (CGFloat)currentZoomScale{
//    return _currentZoomScale > 1 ? _currentZoomScale : 1;
//}

- (UIButton *)saveButton{
    if (!_saveButton) {
        UIButton *saveButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
        saveButton.frame =CGRectMake(JKScreenW - 10 - 50, JKScreenH - 50, 50, 50);
        [saveButton setImage:[UIImage imageNamed:@"Menu_Download"] forState:(UIControlStateNormal)];
        [saveButton addTarget:self action:@selector(saveButtonClick) forControlEvents:(UIControlEventTouchUpInside)];
        [self addSubview:saveButton];
        
        _saveButton = saveButton;
    }
    return _saveButton;
}

- (UIImageView *)imageView{
    if (!_imageView) {
        UIImageView *imageView = [[UIImageView alloc] init];
        [self.scrollView addSubview:imageView];
        imageView.alpha = 0;
        imageView.userInteractionEnabled = YES;
        
        [imageView addGestureRecognizer:[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(imageLongPress:)]];
        
        _imageView = imageView;
    }
    return _imageView;
}

- (UIScrollView *)scrollView{
    if (!_scrollView) {
        UIScrollView *scrollView = [[UIScrollView alloc] init];
        scrollView.frame = [UIScreen mainScreen].bounds;
        [self insertSubview:scrollView atIndex:0];
        
        scrollView.delegate = self;
        
        scrollView.minimumZoomScale = 1;
        scrollView.maximumZoomScale = 2;
        
        scrollView.showsHorizontalScrollIndicator = NO;
        scrollView.showsVerticalScrollIndicator = NO;
        
        scrollView.alwaysBounceVertical = YES;
        scrollView.alwaysBounceHorizontal = YES;
        
        _scrollView = scrollView;
    }
    return _scrollView;
}

- (UIActivityIndicatorView *)indicatorView{
    if (!_indicatorView) {
        
        UIActivityIndicatorView *indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:(UIActivityIndicatorViewStyleWhiteLarge)];
        indicatorView.center = self.center;
        [self addSubview:indicatorView];
        
        _indicatorView = indicatorView;
    }
    return _indicatorView;
}

#pragma mark - 初始化
- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        [self setup];
    }
    return self;
}

- (void)setup{
    self.currentZoomScale = 1;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateSkin) name:JKSkinModelDidChangedNotification object:nil];
    [self updateSkin];
    
    self.scrollView.backgroundColor = [UIColor clearColor];
    self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
    [self.indicatorView startAnimating];
    
    [self saveButton];
    
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selfDismiss)];
    [self addGestureRecognizer:singleTap];
    
    UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTap:)];
    doubleTap.numberOfTapsRequired = 2;
    [self addGestureRecognizer:doubleTap];
    
    [singleTap requireGestureRecognizerToFail:doubleTap];
    
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
}

- (void)doubleTap:(UITapGestureRecognizer *)tap{
    JKLog(@"双击");
    self.isDoubleTap = YES;
    CGPoint touchPoint = [tap locationInView:self.imageView];
    
    CGPoint point = [self.imageView convertPoint:touchPoint fromView:self.imageView];
    
    if (![self.imageView pointInside:point withEvent:nil]) {
        return;
    }
    
    // 双击缩小
    if (self.imageView.frame.size.width > JKScreenW) {
        [self.scrollView setZoomScale:1 animated:YES];
        
        return;
    }
    
    // 双击放大
    [self.scrollView zoomToRect:CGRectMake(touchPoint.x - 5, touchPoint.y - 5, 10, 10) animated:YES];
}

#pragma mark - 事件
- (void)imageLongPress:(UILongPressGestureRecognizer *)gesture{
    if (gesture.state == UIGestureRecognizerStateBegan) {
        UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
        
        UIAlertAction *actionSave = [UIAlertAction actionWithTitle:@"保存图片" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            [self saveButtonClick];
        }];
        UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
        
        [alertVc addAction:actionSave];
        [alertVc addAction:actionCancel];
        
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertVc animated:YES completion:nil];
    }
}

// 保存图片
- (void)saveButtonClick {
    [JKProgressHUD showWithStatus:@"正在保存图片..."];
    
    UIImageWriteToSavedPhotosAlbum(self.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    
    if (error) {
        [JKProgressHUD showErrorWithStatus:@"保存图片失败！"];
        return;
    }
    [JKProgressHUD showSuccessWithStatus:@"保存图片成功！"];
}

// 退出
- (void)selfDismiss{
    // 将self.imageView的坐标系转为self的坐标系
    CGRect imageFrame = [self.scrollView convertRect:self.imageView.frame toView:self];
    
    // 创建要截取的imageView，截取显示在屏幕范围内的self.imageView
    UIImageView *coverImgView = [[UIImageView alloc] init];
    coverImgView.contentMode = UIViewContentModeScaleAspectFit;
    CGFloat X = imageFrame.origin.x > 0 ? imageFrame.origin.x : 0;
    CGFloat Y = imageFrame.origin.y > 0 ? imageFrame.origin.y : 0;
    
    CGFloat maxW = CGRectGetMaxX(imageFrame) > JKScreenW ? JKScreenW : CGRectGetMaxX(imageFrame);
    CGFloat maxH = CGRectGetMaxY(imageFrame) > JKScreenH ? JKScreenH : CGRectGetMaxY(imageFrame);
    
    CGFloat width = maxW - X;
    CGFloat height = maxH - Y;
    
    
    CGRect frame = CGRectMake(X, Y, width, height);
    coverImgView.frame = frame;
    [self addSubview:coverImgView];
    self.maskView.frame = coverImgView.bounds;
    [coverImgView addSubview:self.maskView];
    
    // 截取的范围 即coverImgView转换成self.imageView坐标系后的frame
    CGRect clipRect = [coverImgView.superview convertRect:coverImgView.frame toView:self.imageView];
    
    // 计算原图片与coverImgView尺寸的比例
//    CGFloat scaleW = self.image.size.width / clipRect.size.width;
//    CGFloat scaleH = self.image.size.height / clipRect.size.height;
    // 截取图片
//    CGImageRef imageRef = CGImageCreateWithImageInRect([self.image CGImage], CGRectMake(clipRect.origin.x * scaleW, clipRect.origin.y * scaleH, clipRect.size.width * scaleW, clipRect.size.height * scaleH));
    
    UIGraphicsBeginImageContext(self.imageView.bounds.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [self.imageView.layer renderInContext:context];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    // 截取图片
    CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], clipRect);
    
    UIImage *clipImage = [UIImage imageWithCGImage:imageRef];
    
    CGImageRelease(imageRef);
    
    coverImgView.image = clipImage;
    
    [self.imageView removeFromSuperview];
    
    [UIView animateWithDuration:animationDuration animations:^{
        self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
        coverImgView.alpha = 0;
        coverImgView.transform = CGAffineTransformMakeScale(0.6, 0.6);
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

#pragma mark - 属性赋值
- (void)setImage:(UIImage *)image{
    _image = image;
    
    [self.indicatorView stopAnimating];
    
    CGFloat scale = image.size.width / image.size.height;
    CGFloat imageWidth = JKScreenW;
    CGFloat imageHeight = imageWidth / scale;
    
    // 2.设置图片frame
    self.imageView.image = image;
    self.imageView.frame = CGRectMake(0, 0, imageWidth, imageHeight);
    
    // 3.计算顶部和底部内边距
    CGFloat offsetY = (JKScreenH - imageHeight) * 0.5;
    
    // 4.设置图片位置
    if (imageHeight > JKScreenH) { // 计算后的图片高度 > 屏幕高度
        // 设置contentSize，让长图可以滚动
        self.scrollView.contentSize = CGSizeMake(imageWidth, imageHeight);
        
        // 长图滚到底部翻页后再回来，让它自动回到顶部
        //self.scrollView.contentOffset = CGPointZero;
        
    }else { // 计算后的图片高度 <= 屏幕高度
        // 居中显示使用contentInset，注意底部也要写上，否则可能会出现位置偏移的问题
        self.scrollView.contentInset = UIEdgeInsetsMake(offsetY, 0, offsetY, 0);
    }
    
    self.maskView.frame = self.imageView.bounds;
    
    self.imageView.transform = CGAffineTransformMakeScale(0.1, 0.1);
    
    [UIView animateWithDuration:animationDuration animations:^{
        
        self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:bgAlpha];
        self.imageView.transform = CGAffineTransformIdentity;
        self.imageView.alpha = 1;
        self.maskView.alpha = 1;
        
    } completion:^(BOOL finished) {
        
    }];
}

- (void)setImageUrlStr:(NSString *)imageUrlStr{
    _imageUrlStr = [imageUrlStr copy];
    
    [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:imageUrlStr] options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
        
        [self.indicatorView stopAnimating];
        
        if (error) {
            [JKProgressHUD showErrorWithStatus:@"加载图片失败！"];
            [self selfDismiss];
        }
        if (image != nil) {
            self.image = image;
        }
    }];
}

// 设置自身尺寸总是屏幕尺寸
- (void)setFrame:(CGRect)frame{
    
    frame = [UIScreen mainScreen].bounds;
    
    [super setFrame:frame];
}

#pragma mark - <UIScrollViewDelegate>
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    self.isDoubleTap = NO;
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
    if (scrollView.contentOffset.y < -80 - scrollView.contentInset.top) {
        isGonnaDismiss = YES;
        scrollView.bounces = NO;
        [self selfDismiss];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    NSLog(@"contentOffset --> %@", NSStringFromCGPoint(scrollView.contentOffset));
    if (scrollView.contentOffset.y + scrollView.contentInset.top >= 0) {
        return;
    }
    
    if (self.isZooming || isGonnaDismiss || self.isDoubleTap) {
        return;
    }
    NSLog(@"正在形变！！！");
    self.imageView.transform = CGAffineTransformMakeScale(self.currentZoomScale - (scrollView.contentOffset.y + scrollView.contentInset.top) / (-80 - scrollView.contentInset.top) * 0.7, self.currentZoomScale - (scrollView.contentOffset.y + scrollView.contentInset.top) / (-80 - scrollView.contentInset.top) * 0.7);
    self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:bgAlpha - (scrollView.contentOffset.y + scrollView.contentInset.top) / (-80 - scrollView.contentInset.top)];
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    return self.imageView;
}

- (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view{
    self.isZooming = YES;
}

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale{
    self.currentZoomScale = scale;
    self.isZooming = NO;
    NSLog(@"当前zoomScale ---> %.2f", scale);
}

// 在缩放过程中不断调整位置，使用contentInset
- (void)scrollViewDidZoom:(UIScrollView *)scrollView{
    //JKLog(imageView.bounds) // 从头至尾没有变化
    //JKLog(imageView.frame)  // 相当于contentSize
    //JKLog(scrollview.contentSize)
    
    // 计算内边距，注意只能使用frame
    CGFloat offsetX = (JKScreenW - self.imageView.width) * 0.5;
    CGFloat offsetY = (JKScreenH - self.imageView.height) * 0.5;
    
    // 当小于0的时候，放大的图片将无法滚动，因为内边距为负数时限制了它可以滚动的范围
    offsetX = (offsetX < 0) ? 0 : offsetX;
    offsetY = (offsetY < 0) ? 0 : offsetY;
    self.scrollView.contentInset = UIEdgeInsetsMake(offsetY, offsetX, offsetY, offsetX);
}

#pragma mark - 更新皮肤
- (void)updateSkin{
    NSString *currentSkinModel = [[NSUserDefaults standardUserDefaults] objectForKey:JKCurrentSkinModelKey];

    if ([currentSkinModel isEqualToString:JKNightSkinModelValue]) { // 夜间模式
        self.maskView.hidden = NO;

        
    }else{ // 日间模式
        self.maskView.hidden = YES;
    }
    
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
}
@end
